package com.hupo.dyapp_01.controller;


import com.hupo.dyapp_01.entity.R;
import com.hupo.dyapp_01.entity.User;
import com.hupo.dyapp_01.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.ServletContext;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Random;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    JavaMailSender javaMailSender;
    @Resource
    ServletContext servletContext;
    @Resource
    IUserService userService;

    /**
     * 获取验证码
     */
    @GetMapping("captcha")
    public R getCaptcha(String email)throws MessagingException, UnsupportedEncodingException {
        System.out.println("正在发送验证码...");
        //生成验证码
        int captcha = new Random().nextInt(900000) + 100000;
        //将验证码保存到应用层上下文对象中
        servletContext.setAttribute(email,captcha);
        // 创建一个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();
        // 创建 MimeMessageHelper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        // 发件人邮箱和名称
        helper.setFrom("13886527881@163.com", "昕悦读");
        // 收件人邮箱
        helper.setTo(email);
        // 邮件标题
        helper.setSubject("昕悦读-验证码");
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(captcha+"", true);

        // 发送
        javaMailSender.send(message);
        System.out.println(captcha);

        return R.ok("验证码已发送");
    }

    @PostMapping("registerOrLogin")
    public R registerOrLogin(@RequestBody User user) {
        userService.registerOrLogin(user);
        return R.ok("登录成功");
    }

    /**
     * 修改用户信息
     */
    @PutMapping("update")
    public R updateUser(@RequestBody User user) {
        userService.updateUser(user);
        System.out.println(user);
        return R.ok("用户信息更新成功");
    }

    /**
     * 查询用户
     */
    @GetMapping("getUser")
    public User getUser(String email) {
        return userService.getUser(email);
    }
}
